﻿using UnityEngine;
using System.Collections;

public class MoveToward : MonoBehaviour {
    [SerializeField]
    private float moveDistance = 4f;
    [SerializeField]
    private float delay = 0f;
    [SerializeField]
    private AnimationCurve curve;
    [SerializeField]
    bool useCurve = false;
    [SerializeField]
    float speed = 1f;
    [SerializeField]
    EToward toward;

    enum EToward
    {
        forward,
        up,
        right,
        back,
        down,
        left
    }
    bool canMove = false;
    float moveBeginTime;
    Vector3 originPos;
    Vector3 targetPos;
    Vector3 velocity;
    // Use this for initialization
    void Start () {
        canMove = true;
        moveBeginTime = Time.time + delay;
        velocity = GetToward() * speed;
        targetPos = transform.position + GetToward() * moveDistance;
        originPos = transform.position;
    }
	
	// Update is called once per frame
	void Update () {
	    if(Time.time > moveBeginTime)
        {
            if (useCurve)
            {
                //float percent = Vector3.Distance(transform.position, originPos) / moveDistance;
                //float percent = Mathf.InverseLerp(originPos.x, targetPos.x, transform.position.x);
                //float y = originPos.y +  moveDistance *  curve.Evaluate(percent);
                //float x = transform.position.x - speed * Time.deltaTime;
                //transform.position = new Vector3(x, y, originPos.z);
                float dura = moveDistance / speed;
                float vel = curve.Evaluate((Time.time - moveBeginTime) / dura) ;
                transform.position = Vector3.LerpUnclamped(originPos, targetPos, vel);
                //velocity = GetToward() * vel;
            }
            else
            {
                transform.position = Vector3.SmoothDamp(transform.position, targetPos, ref velocity, (targetPos - transform.position).magnitude / speed, speed, Time.deltaTime);
                //transform.Translate(GetToward() * speed * Time.deltaTime);
            }

            if(Vector3.Distance(transform.position,targetPos) <= 0.01f)
            {
                enabled = false;
            }
        }
	}

    private Vector3 GetToward()
    {
        if(toward == EToward.forward)
        {
            return transform.forward;
        }else if(toward == EToward.back)
        {
            return -transform.forward;
        }
        else if (toward == EToward.down)
        {
            return -transform.up;
        }
        else if (toward == EToward.left)
        {
            return -transform.right;
        }
        else if (toward == EToward.right)
        {
            return transform.right;
        }
        else 
        {
            return transform.up;
        }
    }
}
